<template>
  <div class="formClass hibaoForm column3">
    <el-form ref="ruleForm" v-loading="loading" :inline="true" :model="formData" size="mini">
      <div class="position-height">
        <table>
          <tr>
            <td>
              <el-form-item label="排序字段:">
                <el-select v-model="formData.sortField" popper-class="popperClass" filterable placeholder="请选择">
                  <el-option-group
                    v-for="group in options1"
                    :key="group.key"
                    :label="group.label"
                  >
                    <el-option
                      v-for="item in group.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.show !== true && item.canSearch !== false"
                    />
                  </el-option-group>
                </el-select></el-form-item>
            </td>
            <td>
              <el-form-item label="排序规则:">
                <el-radio v-model="formData.sortRule" label="asc" border size="small">正序</el-radio>
                <el-radio v-model="formData.sortRule" label="desc" border size="small">倒序</el-radio>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="单页显示条数:">
                <el-select v-model="formData.numPerPage" popper-class="popperClass" filterable placeholder="请选择">
                  <el-option
                    v-for="item in options2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </td>
          </tr>
        </table>
        <el-divider />
        <el-table ref="table" :data="tableData" stripe border border height="345" class="innerTable">
          <el-table-column label="字段名称" align="center">
            <template slot-scope="{row}">
              {{ row.label }}
            </template>
          </el-table-column>

          <el-table-column label="显示宽度" align="center">
            <template slot-scope="{row}">
              <el-input v-model="row.width" clearable class="widthClass" placeholder="未填写则自动分配" />
            </template>
          </el-table-column>
          <el-table-column label="是否显示" align="center">
            <template slot-scope="{row}">
              <el-switch
                v-model="row.show"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :disabled="row.disabled"
                @change="switchChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="是否快速查询" align="center">
            <template slot-scope="{row}">
              <el-switch
                v-model="row.quickSearch"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :disabled="!row.canSearch"
                @change="switchChange2(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="显示顺序" align="center">
            <template slot-scope="scope">
              <el-button type="success" icon="el-icon-top" circle :disabled="scope.$index==0" @click.stop="clickUp(scope.$index)" />
              <el-button type="warning" icon="el-icon-bottom" circle style="margin-left: 20px" :disabled="scope.$index==tableData.length-1" @click.stop="clickDowm(scope.$index)" />
            </template>
          </el-table-column>

        </el-table>
      </div>

      <el-form-item class="bottom-btns add-absolute">
        <el-button type="red" @click.stop="save">保存</el-button>
        <el-button type="cancel" @click.stop="cancel">取消</el-button>
        <el-button v-if="userName === 'superadmin'" class="clearSetting" @click.stop="clearSetting">清除设置</el-button>
      </el-form-item>
    </el-form>

  </div>

</template>

<script>
import { savePageSetting, clearSetting } from '@/api/common/systemSet' // api
import { mapGetters } from 'vuex'
export default {
  name: 'PageSetting',
  props: {
    // 自动添加一个key为layerid的值， 该值为创建层的id
    layerid: {
      type: String,
      default: ''
    },
    pageId: {
      type: String,
      default: ''
    },
    sort: {
      type: Object,
      default() {
        return {}
      }
    },
    columns: {
      type: Array,
      default() {
        return []
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId', 'userName'
    ])
  },
  data() {
    return {
      formData: {
        sortField: '',
        sortRule: 'asc',
        numPerPage: 20
      },
      tableData: [],
      loading: false,
      options1: [],
      options2: [
        { value: 15, label: '15条/页' },
        { value: 50, label: '50条/页' },
        { value: 100, label: '100条/页' },
        { value: 300, label: '300条/页' }
      ]
    }
  },
  mounted() {
    this.$store.commit('app/SET_LAYERID', this.layerid)
    this.formData.sortField = this.sort.prop
    this.formData.sortRule = this.sort.order
    this.formData.numPerPage = this.sort.pageSize
    this.handleRow().then(() => {
      this.initSortFieldData()
    })
  },
  methods: {
    // 重置按钮
    reset() {
    },
    save() {
      this.loading = true
      const saveData = {}
      saveData.sortSetting = JSON.stringify(this.formData)
      saveData.fieldSetting = JSON.stringify(this.tableData)
      saveData.pageId = this.pageId
      saveData.bandUserId = this.userId
      saveData.createUserName = this.userName
      saveData.createUser = this.userId
      saveData.lastUpdateUser = this.userId
      // 保存页面设置
      savePageSetting(saveData).then(res => {
        if (res && res.result === 'success') {
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 1000
          })
          this.loading = false
          this.$layer.close(this.layerid) // 关闭弹框
          this.$parent.initPageSetting() // 调用父组件的刷新方法
        }
      })
    },
    // 向上移动一行
    clickUp(index) {
      // tableData里，当前 index 的值 与 index-1 的值交换
      const cacheData1 = this.tableData[index]
      const cacheData2 = this.tableData[index - 1]
      // 使用 $set 方法，可以在修改数组时，让VUE监听到数组的变化
      // https://cn.vuejs.org/v2/guserIde/reactivity.html#对于数组
      this.$set(this.tableData, index, cacheData2)
      this.$set(this.tableData, index - 1, cacheData1)
      // 排序字段选择框数据源初始化
      this.initSortFieldData()
    },
    // 向下移动一行
    clickDowm(index) {
      // tableData里，当前 index 的值 与 index+1 的值交换
      const cacheData1 = this.tableData[index]
      const cacheData2 = this.tableData[index + 1]
      // 使用 $set 方法，可以在修改数组时，让VUE监听到数组的变化
      // https://cn.vuejs.org/v2/guserIde/reactivity.html#对于数组
      this.$set(this.tableData, index, cacheData2)
      this.$set(this.tableData, index + 1, cacheData1)
      // 排序字段选择框数据源初始化
      this.initSortFieldData()
    },
    // 是否显示选择框改变触发
    switchChange(row) {
      // 遍历所有的行,如果所有的行都不显示,阻止此次操作
      if (JSON.stringify(this.tableData.filter(item => item.show)) === '[]') {
        this.$message({
          type: 'warning',
          message: '至少有一个字段显示',
          duration: 2000
        })
        row.show = true // 当前行 show 设为 true
        return // 不往下走了
      }

      // 排序字段选择框数据源初始化
      this.initSortFieldData()
      // 如果当前行不显示了，看看已经选择的排序字段是不是这个要关闭的行
      // 如果是的话，把排序字段选择框置为默认（按最后更新时间倒序）
      if (this.formData.sortField === row.prop) {
        this.formData.sortField = 'lastUpdateTime'
        this.formData.sortRule = 'desc'
        this.$alert('默认排序字段已隐藏，排序默认按更新时间倒序排序。')
      }
    },
    // 是否快速查询 - 选择框改变时触发
    switchChange2(row) {
      // 遍历所有的行,如果所有的行都不能快速查询,阻止此次操作
      if (JSON.stringify(this.tableData.filter(item => item.quickSearch)) === '[]') {
        this.$message({
          type: 'warning',
          message: '至少有一个字段支持快速查询',
          duration: 2000
        })
        row.quickSearch = true // 当前行 quickSearch 设为 true
      }
    },
    // 排序字段选择框数据源初始化
    initSortFieldData() {
      const _this = this
      _this.options1 = []
      const cacheArray1 = []
      _this.tableData.forEach(item => {
        const cacheData = {}
        cacheData.key = item.prop
        cacheData.value = item.prop
        // cacheData.label = this.$t(this.pageId + '.' + item.prop)
        cacheData.label = item.label
        cacheData.show = item.show && item.canSearch // 如果这行不显示了，选择框中的此项也要禁止掉
        cacheArray1.push(cacheData)
      })
      const cacheData1 = {
        key: 1,
        label: '',
        options: cacheArray1
      }
      _this.options1.push(cacheData1)
      const cacheData2 = {
        key: 2,
        label: '',
        options: [
          {
            key: 'autoCreateTime1',
            value: 'autoCreateTime',
            label: '创建时间',
            show: true
          },
          {
            key: 'lastUpdateTime1',
            value: 'lastUpdateTime',
            label: '更新时间',
            show: true
          }
        ]
      }
      _this.options1.push(cacheData2)
    },
    // 处理传过来的行数据
    handleRow() {
      return new Promise((resolve, reject) => {
        const resData = []
        const cacheData = this.columns
        // 补全columns中缺失的字段
        cacheData.forEach(item => {
          if (typeof (item.show) === 'undefined') { item.show = true }
          if (typeof (item.quickSearch) === 'undefined') { item.quickSearch = false }
          if (typeof (item.canSearch) === 'undefined') { item.canSearch = true }
          resData.push(item)
        })
        this.tableData = resData
        resolve(resData)
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    clearSetting() {
      const json = {
        pageId: this.pageId
      }
      clearSetting(json).then(res => {
        if (res && res.result === 'success') {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1000
          })
          this.$layer.close(this.layerid) // 关闭弹框
          this.$refreshTag(this.$route.path)// 刷新当前标签页
        }
      })
    }
  }
}
</script>

<style scoped>
  .el-radio.is-bordered.is-checked{
    border-color:#8f0000
  }
  .tableClass >>> table{
    margin-top: 0px;
  }
  .widthClass >>> input{
    /*border: 0px;*/
    background-color: unset;
    text-align: center;
  }

  .formClass.column3 .innerTable >>> .el-button{
    padding: 7px;
  }
  .formClass.column3  >>> .el-divider--horizontal{
    margin: 12px 0px 26px 0px;
  }

  .clearSetting{
    float: left;
    margin-left: 12px !important;
  }
</style>
